<?php

namespace addons\epay\controller;


use addons\epay\library\Service;
use app\admin\model\Order;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use think\Db;

class Wxtuikuan
{

    public function tuikuan($order_id)
    {
//        $order_id = input('order_id');
        if (!$order_id){
            return json_encode(['code' => 0,'msg' => '订单id不能为空', 'data' => []]);
        }
        $config2 = Service::getConfig('wechat');

        $config = [
            'appid' => '', // APP APPID
            'app_id' => '', // 公众号 APPID
            'miniapp_id' => $config2['miniapp_id'], // 小程序 APPID
            'mch_id' => $config2['mch_id'],
            'key' => $config2['key'],
            'notify_url' => $config2['notify_url'],
            'cert_client' => '/www/wwwroot/2037.cs/addons/epay/certs/apiclient_cert.pem', // optional，退款等情况时用到
            'cert_key' => '/www/wwwroot/2037.cs/addons/epay/certs/apiclient_key.pem',// optional，退款等情况时用到
            'log' => [ // optional
                'file' => '/www/wwwroot/2037.cs/runtime/log/epaylogs/wechat-2022-08-31.log',
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 10,
                'connect_timeout' => 10,
                // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
            ],
            'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为中国香港 gateway。
        ];

        $order = Order::where('id', $order_id)->find();
        if (empty($order))
        {
            return json_encode(['code' => 0,'msg' => '订单不能存在', 'data' => []]);
        }
        if ($order['t_status'] == 1){
            return json_encode(['code' => 0,'msg' => '退款已提交,请勿重复申请', 'data' => []]);
        }
        Order::where('id', $order_id)->update(['t_status' => 1]);

        $orders = [
            'out_trade_no' => $order['number'],
            'out_refund_no' => time(),
            'total_fee' => $order['price'] * 100,
            'refund_fee' => $order['price'] * 100,
            'refund_desc' => $order['title'],
            'type' => 'miniapp',

        ];

        $pay = Pay::wechat($config)->refund($orders);

        $data = [
            'code' => 1,
            'msg' => '退款成功',
            'data' => $pay,
        ];
        return json_encode($data);
//         $pay->appId;
        // $pay->timeStamp
        // $pay->nonceStr
        // $pay->package
        // $pay->signType
    }

    public function notifyx()
    {
        $testxml = file_get_contents("php://input");

        try{
            $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));

            Db::name('ot')->insert(['content' => $jsonxml]);

            $result = json_decode($jsonxml, true);
            $data = $this->jiemi($result['req_info']);

            if($data){
                if($data['refund_status'] == 'SUCCESS' ){

                    Order::where('number',$data['out_trade_no'])->update(['status' => 6]);
                }
            }

        } catch (\Exception $e) {
            // $e->getMessage();
        }

        echo "success";

    }


    public function jiemi($req_info)
    {

        //退款的加密信息
        $api_key ='9bdaa35c0e6a49eec0f345595ac26eb2';
        // 对加密信息进行解密,需要用到商户秘钥
        $req_info_xml = openssl_decrypt(base64_decode($req_info), 'aes-256-ecb',md5($api_key),OPENSSL_RAW_DATA);
        $jsonxml = json_encode(simplexml_load_string($req_info_xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $arr =  json_decode($jsonxml, true);

        return $arr;
    }
}
